package com.tianheng.modbus.nettyservice;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

import static com.tianheng.modbus.service.InBoundHandler.getIPString;



/**************************************************
 * copyright (c) 2020, peng.cao@tianheng-uestc.com All Rights Reserved.
 * created by peng.cao
 * date:       2020/7/6 0006
 * since:      1.0.0.1
 * description:
 *
 **************************************************/
@Slf4j
@Component
@ChannelHandler.Sharable
public class DataServerHandler extends ChannelInboundHandlerAdapter {


    private static final ByteBuf HEART_BEAT =  Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("心跳连接", CharsetUtil.UTF_8));
    /**
     * 当我们通道进行激活的时候 触发的监听方法
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.err.println("客户端加入连接："+ctx.channel());
        Server.map.put(getIPString(ctx), ctx.channel());
    }

    /**
     * 当我们的通道里有数据进行读取的时候 触发的监听方法
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx , Object msg ) throws Exception {

        ByteBuf result = Unpooled.copiedBuffer(msg.toString(), CharsetUtil.UTF_8);
//        ByteBuf result = (ByteBuf) msg;
        System.err.println("指令来源于"+ctx.channel().remoteAddress().toString());
        byte[] result1 = new byte[result.readableBytes()];
        result.readBytes(result1);
        String resultStr = new String(result1);
        System.out.println(resultStr);

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.err.println( "--------数据读取完毕----------");
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Server.map.remove(getIPString(ctx));
        Server.macMap.remove(getIPString(ctx));
        ctx.close();

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println( "--------数据读异常----------: ");
        cause.printStackTrace();
        ctx.close();
    }


    public String getRemoteAddress(ChannelHandlerContext ctx) {
        String socketString = "";
        socketString = ctx.channel().remoteAddress().toString();
        return socketString;
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt ;
            if (idleStateEvent.state() == IdleState.READER_IDLE){
                log.info("已经10秒没有收到信息！");
                ctx.writeAndFlush(HEART_BEAT).addListener(ChannelFutureListener.CLOSE_ON_FAILURE) ;
            }
        }

        super.userEventTriggered(ctx, evt);
    }
}
